/*
 * @Author: gy
 * @Date: 2020-04-01 11:33:02
 * @LastEditors: gy
 * @LastEditTime: 2021-03-17 13:21:42
 */
let app = require("express")();
let fs = require("fs");
let https = require("http");
let readLine = require("readline");
const moment = require("moment");
const sleep = 1000;
let domain_url = "http://geo.datav.aliyun.com/areas_v2/bound/";

function readFileToArr(fReadName, cb) {
  var arr = [];
  var readObj = readLine.createInterface({
    input: fs.createReadStream(fReadName),
  });

  readObj.on("line", function (line) {
    arr.push(line.match(/[0-9]+/g)[0]);
  });
  readObj.on("close", function () {
    console.log("readLine close....");
    cb(arr);
  });
}

async function saveJsonFile(url, code) {
  if (!code) return console.error('未获取到code');
  let datas = [];
  return new Promise((resolve) => {
    https
      .get(url, { timeout: 60000 }, (res) => {
        res
          .on("data", (d) => {
            datas.push(d);
          })
          .on("end", () => {
            let buffer = Buffer.concat(datas);
            try {
              let test_res = JSON.parse(buffer.toString());
              fs.writeFileSync(
                __dirname + "/20210317_json/" + code + ".json",
                buffer.toString(),
                { flag: "w+" }
              );

              setTimeout(() => {
                resolve(true);
              }, sleep);
            } catch (error) {
              //如果没有完整地图，下载当前地图
              if (
                buffer.toString().indexOf("The specified key does not exist") !=
                -1
              ) {
                let url = `${domain_url}${code}.json`;
                saveJsonFile(url, code);
              } else {
                err_log(`${code}获取失败`);
              }

              setTimeout(() => {
                resolve(true);
              }, sleep);
            }
          });
      })
      .on("error", (e) => {
        err_log(`${code}获取失败`);

        setTimeout(() => {
          resolve(true);
        }, sleep);
      });
  });
}

readFileToArr("./中国行政区域代码.txt", async function (arr) {
  for(const item of arr){
    if (!item) return;
    let postUrl = domain_url + item + "_full.json";
    await saveJsonFile(postUrl, item); 
    console.log(`正在处理:${item}`)
  }
});

// fs.readFile('./中国行政区域代码.txt','utf-8',(err,res)=>{
//   if(err) return console.log(JSON.stringify(err))
//   console.log(res)
// })

function err_log(msg) {
  console.log(msg)
  fs.writeFileSync(
    __dirname + "/err.log",
    `${msg}  [${moment().format("YYYY-MM-DD hh:mm:ss")}]\n`,
    { flag: "a+" }
  );
}

let server = app.listen("3000", () => {
  console.log("server at port 3000");
});

server.setTimeout(0);
